import Taro from "@tarojs/taro";
import { useLocationStore } from "../store";
import * as cityApi from "../api/city";
import { useUserStore } from "../store";

export async function getLocation() {
  const locationStore = useLocationStore();
  const userStore = useUserStore();
  await locationStore.getAllCitydata();

  // const res: any = await cityApi.getLocationMesage({
  //   lat: "38.03781154197048",
  //   lng: "114.61772733437438",
  // });
  // console.log(res);

  // if (res.state == 200 && res.data.id) {
  //   locationStore.setLocation("38.03781154197048", "114.61772733437438", {
  //     id: res.data.id,
  //     cityName: res.data.city,
  //   });
  // } else {
  //   Taro.showToast({
  //     title: res.message,
  //     icon: "error",
  //   });
  // }

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(async (position) => {
      const res: any = await cityApi.getLocationMesage({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      });
      if (res.state == 200 && res.data.id) {
        locationStore.setLocation(
          position.coords.latitude,
          position.coords.longitude,
          {
            id: res.data.id,
            cityName: res.data.city,
          }
        );
      } else {
        Taro.showToast({
          title: res.message,
          icon: "error",
        });
      }
    });
  } else {
    alert("您的设备不支持定位功能");
  }

  // 首先定义一个获取位置的函数

  // locationStore.setLocation(res["city"]);
  // Taro.getLocation({
  //   success: (res) => {
  //     locationStore.setLocation(res["latitude"], res["longitude"], res["city"]);
  //     const selectCityinfo = locationStore.selectCityinfo;
  //     if (!selectCityinfo) {
  //       return;
  //     }
  //     if (!res["city"].includes(selectCityinfo.cityName)) {
  //       // 如果当前获取的城市与已选择的城市不一致
  //       Taro.showModal({
  //         title: "位置更新",
  //         content: `是否切换城市为【${res["city"]}】`,
  //         success: (res) => {
  //           if (res.confirm) {
  //             locationStore.setSelectCityinfo(locationStore.currentCityinfo);
  //           }
  //         },
  //       });
  //     }
  //   },
  //   fail: (error) => {
  //     // console.log(error);
  //     setTimeout(() => {
  //       Taro.navigateTo({
  //         url: "/pages/select-city/index",
  //       });
  //     }, 500);
  //   },
  //   complete: (res) => {
  //     console.log(res);
  //   },
  // });
}
